/**
 * Project Name:fastPlat
 * File Name:PermissionServiceImpl.java
 * Package Name:com.fast.user.service.admin.impl
 * Date:2014年12月17日下午1:43:54
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.user.service.admin.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.util.data.MathUtils;
import com.fast.user.model.admin.Group;
import com.fast.user.model.admin.Permission;
import com.fast.user.model.admin.dto.MenuDTO;
import com.fast.user.service.admin.PermissionService;

/**
 * ClassName:PermissionServiceImpl <br/>
 * 用途: 权限服务 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午1:43:54 <br/> 	 
 */
@Service("permissionService")
public class PermissionServiceImpl extends JpaDaoSupport implements PermissionService {
	
	
	/**
	 * 获取权限内容
	 * @param groupUUID
	 * @return
	 * @author lushuifa242
	 */
    @Override
	public String getPermissionArray(String groupUUID){
		return super.queryColumn(" select permissionArray from "+AbstractSqlGenerator.getTableName(Group.class)+" where uuid='"+groupUUID+"'").toString();
	}
	
	
	/**
	 * 拷贝权限
	 * @param toPermissitonId
	 * @param uuidArray
	 * @author lushuifa242
	 * @return
	 */
    @Override
	@CacheEvict(value="permission",allEntries=true)
	public boolean copyPermission(String toPermissitonId, String uuidArray){
		 boolean actionFlag = false;
		 try {
			 String[] uuidArrays = uuidArray.split("`");
			 for (String copyUUID : uuidArrays) {
				 if(StringUtils.isNotEmpty(copyUUID)){
					 Permission copyPermission = super.queryForBeanByUUID(Permission.class, copyUUID);
					 //更换父级达到copy的效果
					 copyPermission.setParentUUID(toPermissitonId);
					 copyPermission.setUuid(MathUtils.getTheOnlyStr());
					 //处理唯一编码
					 String psmCode = genPsmCode(copyPermission);
					 copyPermission.setPsmCode(psmCode);
					 super.saveOrModify(copyPermission, " where uuid='"+copyPermission.getUuid()+"'");
				 }
			 }
			 actionFlag = true;
		 } catch (Exception e) {
			 actionFlag = false;
			 e.printStackTrace();
		 }
		 return actionFlag;
	}
	
	
	/**
	 * 得到字典树状结构数据
	 * TODO 简单描述该方法的实现功能（可选）.
	 * @author lushuifa242
	 * @see com.fast.cms.service.system.DictionaryService#getDicTreeData(java.lang.String)
	 */
	@Override
	@Cacheable(value="permission",key="'getPermissionTreeData_'+#parentUUID")
	public JSONArray getPermissionTreeData(String parentUUID,boolean isRoot) {
		if(parentUUID.equals("0")){
			JSONObject jsonOBject = new JSONObject();
			jsonOBject.put("id", 0);
			jsonOBject.put("text", "权限根目录");
			jsonOBject.put("iconCls", "icon-folderPage");
			jsonOBject.put("children", getPermissionTreeJsonData("0"));
			//新增属性对象
			JSONObject attributes = new JSONObject();
			attributes.put("parentUUID","0");
			attributes.put("parentTitle","最上层");
			attributes.put("psmCode","DIC");
			//添加其它属性
			jsonOBject.put("attributes", attributes);
			JSONArray jsonArray = new JSONArray();
			jsonArray.add(jsonOBject);
			return jsonArray;
		}else{
			if(isRoot){
				Permission permission = super.queryForBeanByUUID(Permission.class, parentUUID);
				JSONObject jsonOBject = new JSONObject();
				jsonOBject.put("id", permission.getUuid());
				jsonOBject.put("text", permission.getPsmName());
				jsonOBject.put("iconCls", "icon-folderPage");
				jsonOBject.put("children", getPermissionTreeJsonData(parentUUID));
				//新增属性对象
				JSONObject attributes = new JSONObject();
				attributes.put("parentUUID",permission.getParentUUID());
				attributes.put("parentTitle",permission.getParentName());
				attributes.put("psmCode",permission.getPsmCode());
				//添加其它属性
				jsonOBject.put("attributes", attributes);
				JSONArray jsonArray = new JSONArray();
				jsonArray.add(jsonOBject);
				return jsonArray;
			}else{
				return getPermissionTreeJsonData(parentUUID);
			}
			
		}
	}
	
	/**
	 * getTreeJson:(得到字典树结构数据). <br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	public JSONArray getPermissionTreeJsonData(String parentUUID){
		//查出当前列表
		String sql = "select uuid,parentUUID,parentName,psmCode,psmName,psmDesc from "+AbstractSqlGenerator.getTableName(Permission.class)+" where parentUUID='"+parentUUID+"' order by orderNo asc";
		List<Map<String, Object>> permissionList = super.queryForMapList(sql);
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonOBject = null;
		if(permissionList.size()>0){
			for (Map<String, Object> map : permissionList) {
			    jsonOBject = new JSONObject();
			    jsonOBject.put("id", map.get("uuid"));
				jsonOBject.put("text",map.get("psmName"));
				//判断是否存在下级
				boolean flag = super.isExist(Permission.class,"where parentUUID='"+map.get("uuid")+"'");
				if(flag){
					jsonOBject.put("state","closed");
					jsonOBject.put("iconCls", "icon-folderPage");
					//递归回调
					//jsonOBject.put("children", getPsmTreeJsonData(map.get("uuid").toString()));
				}else{
					jsonOBject.put("iconCls", "icon-page");
				}
				//新增属性对象
				JSONObject attributes = new JSONObject();
				attributes.put("parentUUID",map.get("parentUUID"));
				attributes.put("parentName",map.get("parentName"));
				attributes.put("psmCode",map.get("psmCode"));
				//添加其它属性
				jsonOBject.put("attributes", attributes);
				jsonArray.add(jsonOBject);
			}
		}
		return jsonArray;
	}
	
	
	//得到权限相关数据,返回数据为JSONArray===开始=================================
	/**
	 * 标题：getTreeGridData <br/>
	 * 作用：得到权限树结构数据     <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public JSONArray getTreeForJsonArray(String parentUUID,String pmsArr,int depth){
		depth--;
		JSONArray jsonArray = new JSONArray();
		List<Permission> psimList = this.queryForBeanList(Permission.class, " where parentUUID='"+parentUUID+"' and viewMode=1 order by orderNo asc");
		if(null!=pmsArr){
			if(!pmsArr.equals("all")){
				psimList = filterList(psimList,pmsArr);
			}
			if(!psimList.isEmpty()&&psimList!=null){
				JSONObject jsonObject = null;
				for (Permission permission : psimList) {
					jsonObject = (JSONObject) JSON.toJSON(permission);
					if(depth>0){
						if(super.isExist(Permission.class, " where parentUUID='"+permission.getUuid()+"'")){
							jsonObject.put("children",getTreeForJsonArray(permission.getUuid(),pmsArr,depth));
						}
					}
					jsonArray.add(jsonObject);
				}
			}
		}
		return jsonArray;
	}
	
	//过滤列表,过滤无相关权限的资源
    private List<Permission> filterList(List<Permission> psimList,String pmsArr) {
		List<Permission> newPsimList = new ArrayList<Permission>();
		for (Permission permission : psimList) {
			String curPmsCode = "["+permission.getPsmCode()+"]";
			if(pmsArr.contains(curPmsCode)){
				newPsimList.add(permission);
			}
		}
		return newPsimList;
	}
	
	//得到权限相关数据,返回数据为JSONArray===结束=================================
	
	/**
	 * 保存修改权限信息
	 * @param permission
	 * @return
	 */
	@Override
	@CacheEvict(value="permission",allEntries=true)
	public boolean saveOrUpdatePermission(Permission permission){
		return super.saveOrModify(permission, " where uuid='"+permission.getUuid()+"'");
	}
	
	/**
	 * 获取系统左侧二级菜单
	 */
	@Override
	//@Cacheable(value="permission",key="'SystemLeftMenu_'+#groupId")
	public List<MenuDTO> getSystemLeftMenu(int groupId) {
		List<MenuDTO> menuList = new ArrayList<MenuDTO>();
		try {
			//得到当前角色对应的权限信息
			Group group = super.getById(Group.class, groupId);
			String permissionArray = group.getPermissionArray();
			//获取一级菜单 
			List<Permission> pmsList = super.queryForBeanList(Permission.class, " where parentUUID='0' order by orderNo asc");
			MenuDTO menuDto = null;
			for (Permission permission : pmsList) {
				if(permissionArray.contains("["+permission.getPsmCode()+"]:"+permission.getPsmName())){
					menuDto = new MenuDTO();
					BeanUtils.copyProperties(menuDto, permission);
					//查询二级菜单
					List<Permission> childPmsList = super.queryForBeanList(Permission.class, " where parentUUID='"+permission.getUuid()+"' order by orderNo asc");
					List<MenuDTO> childMenuList = new ArrayList<MenuDTO>();
					MenuDTO childMenu = null;
					for (Permission childPms : childPmsList) {
						if(permissionArray.contains("["+childPms.getPsmCode()+"]:"+childPms.getPsmName())){
							childMenu = new MenuDTO();
							BeanUtils.copyProperties(childMenu, childPms);
							childMenuList.add(childMenu);
						}
					}
					menuDto.setChildList(childMenuList);
					menuList.add(menuDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return menuList;
	}
	
	/**
	 * 标题：getTreeGridData <br/>
	 * 作用：得到权限树结构数据     <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public JSONArray getTreeGridData(String parentUUID){
		if(parentUUID.equals("0")){
			Permission root = new Permission();
			root.setId(0);
			root.setUuid("0");
			root.setParentName("-1");
			root.setParentUUID("-1");
			root.setPsmCode("-1");
			root.setPsmName("权限根目录");
			root.setPsmUrl("#");
			JSONObject rootJo = (JSONObject) JSONObject.toJSON(root);
			rootJo.put("iconCls","icon-folderPage");
			JSONArray jsonArray = new JSONArray();
			rootJo.put("children", getTreeGridList(parentUUID));
			jsonArray.add(rootJo);
			return jsonArray;
		}else{
			return getTreeGridList(parentUUID);
		}
	}
	
	/**
	 * 标题：getTreeGridData <br/>
	 * 作用：得到树导航数据     <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public JSONArray getPsmTreeData(String parentUUID,String permissionArray,String cacheKey){
		if(parentUUID.equals("0")){
			JSONObject jsonOBject = new JSONObject();
			jsonOBject.put("id", 0);
			jsonOBject.put("text", "权限根目录");
			jsonOBject.put("iconCls", "icon-folderPage");
			jsonOBject.put("children", getPsmTreeJsonData("0",permissionArray));
			//新增属性对象
			JSONObject attributes = new JSONObject();
			attributes.put("parentUUID","0");
			attributes.put("parentTitle","最上层");
			attributes.put("psmCode","zm0");
			//添加其它属性
			jsonOBject.put("attributes", attributes);
			JSONArray jsonArray = new JSONArray();
			jsonArray.add(jsonOBject);
			return jsonArray;
		}else{
			return this.getPsmTreeJsonData(parentUUID,permissionArray);
		}
	}
	
	/**
	 * getTreeJson:(得到权限树结构数据). <br/>
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	private JSONArray getPsmTreeJsonData(String parentUUID,String permissionArray){
		//查出当前列表
		//List<Permission> permissionList = super.findList();
		String sql = "select uuid,parentUUID,parentName,psmCode,psmName from "+AbstractSqlGenerator.getTableName(Permission.class)+" where parentUUID='"+parentUUID+"' order by orderNo asc";
		List<Map<String, Object>> permissionList = super.queryForMapList(sql);
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonOBject = null;
		if(permissionList.size()>0){
			for (Map<String, Object> permission : permissionList) {
				jsonOBject = new JSONObject();
			    jsonOBject.put("id", permission.get("uuid"));
				jsonOBject.put("text",permission.get("psmName"));
				//判断已有权限是否存在该节点，存在则选中
				String pmsStr = "["+permission.get("psmCode")+"]:"+permission.get("psmName");
				if(permissionArray.contains(pmsStr)){
					jsonOBject.put("checked",true);
				}else{
					jsonOBject.put("checked",false);
				}
				//判断是否存在下级
				boolean flag = super.isExist(Permission.class,"where parentUUID='"+permission.get("uuid")+"'");
				if(flag){
					jsonOBject.put("state","open");
					jsonOBject.put("iconCls", "icon-folderPage");
					//递归回调
					jsonOBject.put("children", getPsmTreeJsonData(permission.get("uuid").toString(),permissionArray));
				}else{
					jsonOBject.put("iconCls", "icon-page");
				}
				//新增属性对象
				JSONObject attributes = new JSONObject();
				attributes.put("parentUUID",permission.get("parentUUID"));
				attributes.put("parentTitle",permission.get("parentName"));
				attributes.put("psmCode",permission.get("psmCode"));
				//添加其它属性
				jsonOBject.put("attributes", attributes);
				jsonArray.add(jsonOBject);
			}
		}
		return jsonArray;
	}
    
	/**
	 * 标题：getTreeGridList <br/>
	 * 作用：   获取列表  <br/>
	 * @author developer-lushuifa
	 * @param parentUUID
	 * @return
	 * @since JDK 1.6
	 */
	private JSONArray getTreeGridList(String parentUUID) {
		JSONArray jsonArray = new JSONArray();
		List<Permission> psimList = this.queryForBeanList(Permission.class, " where parentUUID='"+parentUUID+"' order by orderNo asc");
		if(!CollectionUtils.isEmpty(psimList)){
			JSONObject jsonObject = null;
			for (Permission permission : psimList) {
				jsonObject = (JSONObject) JSONObject.toJSON(permission);
				if(super.isExist(Permission.class, " where parentUUID='"+permission.getUuid()+"'")){
					jsonObject.put("state","closed");
					jsonObject.put("iconCls","icon-folderPage");
				}else{
					jsonObject.put("iconCls","icon-page");
				}
				jsonArray.add(jsonObject);
			}
		}
		return jsonArray;
	}
	
	/**
	 * 说明: 顺序调整 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年10月12日 下午10:55:09 </pre>
	 * @param 
	 * @author lushuifa242
	 */
	@Override
	public boolean setOrderVal(String setType, int id){
		boolean actionFlag = false;
		try {
			Permission curPermission = super.queryForBeanById(Permission.class, id);
			List<Permission> psmList = super.queryForBeanList(Permission.class, "where parentUUID='"+curPermission.getParentUUID()+"'  order by orderNo asc");
			int index = 1;
			for (Permission permission : psmList) {
				permission.setOrderNo(index);
				saveOrUpdatePermission(permission);
				index++;
			}
			curPermission = super.queryForBeanById(Permission.class, id);
			if(StringUtils.equals(setType, "up")){
				String sql = "update "+SqlGeneratorImpl.getTableName(Permission.class)+" set orderNo=orderNo-1 where id="+curPermission.getId();
				super.modifyRow(sql);
				String sql2 = "update "+SqlGeneratorImpl.getTableName(Permission.class)+" set orderNo=orderNo+1 where parentUUID="+curPermission.getParentUUID()+" and orderNo="+(curPermission.getOrderNo()-1);
				super.modifyRow(sql2);
			}else{
				String sql = "update "+SqlGeneratorImpl.getTableName(Permission.class)+" set orderNo=orderNo+1 where id="+curPermission.getId();
				super.modifyRow(sql);
				String sql2 = "update "+SqlGeneratorImpl.getTableName(Permission.class)+" set orderNo=orderNo-1 where parentUUID="+curPermission.getParentUUID()+" and orderNo="+(curPermission.getOrderNo()+1);
				super.modifyRow(sql2);
			}
			actionFlag = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return actionFlag;
	}
	
	// 生成权限编码
	@Override
	public String genPsmCode(Permission permission) {
	   String psimCode = "P";
	   int count = this.count(Permission.class, " where parentUUID='"+permission.getParentUUID()+"'");
	   //取出父级
	   if(permission.getParentUUID().equals("0")){
		   psimCode+="A"+count+"E";
	   }else{
		   Permission parent = this.queryForBean(Permission.class, " where uuid='"+permission.getParentUUID()+"'");
		   psimCode+=(parent.getPsmCode().replace("E", "").replace("P", ""))+genPsmCode(parent.getGrade())+count+"E";
	   }
	   return psimCode;
	}
	
	/**
	 * 标题：genPsmGrade <br/>
	 * 作用：获取当前对象就有的级别     <br/>
	 * @author developer-lushuifa
	 * @param permission
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public int genPsmGrade(Permission permission){
		if(permission.getParentUUID().equals("0")){
			return 1;
		}else{
			Permission parent = this.queryForBean(Permission.class, " where uuid='"+permission.getParentUUID()+"'");
		    return parent.getGrade()+1;
		}
	}
	
	/**
	 * 标题：genOrderNo <br/>
	 * 作用：  获取排序字段值   <br/>
	 * @author developer-lushuifa
	 * @param permission
	 * @return
	 * @since JDK 1.6
	 */
	@Override
	public int genOrderNo(Permission permission){
		try {
			return this.countBySql("select max(orderNo) orderNo from T_dv_Permission where parentUUID='"+permission.getParentUUID()+"'")+1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
    
	private String genPsmCode(int grade) {
		String[] codes = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        if(grade>0&&grade<=26){
        	return codes[grade];
		}
        return "PSIM";
	}
}

